# -*- coding: utf-8 -*-

from datetime import datetime
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.api import memcache
from common import *
from model import *

class Info(webapp.RequestHandler):
    def get(self, userId):
        userId = int(userId)
        user = User.get_by_id(userId)
        if user:
            self.response.out.write(templates.get_template('user.html').render(user=user))
        else:
            self.response.out.write(templates.get_template('404.html').render())


class MyInfo(webapp.RequestHandler):
    def get(self):
        currentUser = users.get_current_user()
        if currentUser:
            user = User.all().filter('user = ', currentUser).get()
            registering = False
            if not user:
                user = User(user=currentUser, name=' ', classification=0)
                registering = True
            self.response.out.write(templates.get_template('my.html').render(user=user, registering=registering))
        else:
            self.redirect(users.create_login_url(self.request.uri))

    def post(self):
        currentUser = users.get_current_user()
        if not currentUser:
            self.redirect(users.create_login_url(self.request.uri))
        else:
            name = self.request.get('name')
            name = name or name.strip()
            if not name:
                self.response.out.write(templates.get_template('msg.html').render(title=u'请求错误', body=u'用户名不能为空。'))
                return
            
            def parse(string, default, func=str):
                try:
                    i = long(string)
                    return func(i) if func != long else i
                except:
                    return default
                
            classification = parse(self.request.get('classification'), -1, long)
            if classification < 0 or classification > 2:
                self.response.out.write(templates.get_template('msg.html').render(title='请求错误', body='参数错误或不完整。'))
                return
            
            qq_line = parse(self.request.get('qq_line'), '')
            fm_line = parse(self.request.get('fm_line'), '')
            registering = self.request.get('registering') == 'yes'
            
            CACHE_TIME_OUT = 35 # 响应最多30秒，这里设为35秒，保证响应期间memcache都有效
            id = currentUser.user_id()

            if registering:
                if not memcache.add(id, True, namespace='user_registering', time=CACHE_TIME_OUT): # add失败表示已在注册中了。memcache是事务性的，可以用这种方法加锁。
                    self.response.out.write(templates.get_template('msg.html').render(title='注册错误', body='请勿重复注册。'))
                    return
                
                if not memcache.add(name, id, namespace='user_name', time=CACHE_TIME_OUT):
                    self.response.out.write(templates.get_template('msg.html').render(title='注册错误', body='已有同名账号存在，无法完成注册请求。'))
                    return

            user = User.all().filter('user = ', currentUser).get()
            if registering and user:
                self.response.out.write(templates.get_template('msg.html').render(title='注册错误', body='请勿重复注册。'))
            elif not registering and not user:
                self.response.out.write(templates.get_template('msg.html').render(title='请求错误', body='参数错误或不完整。'))
            else:
                if user and name != user.name and (
                    not memcache.add(name, id, namespace='user_name', time=CACHE_TIME_OUT) or # 缓存中没有同时改名的
                    User.all().filter('name = ', name).count(1)): # 数据库中也没有名字为这个的用户存在
                    self.response.out.write(templates.get_template('msg.html').render(title='注册错误', body='已有同名账号存在，无法完成改名请求。'))
                    return
                elif not user and User.all().filter('name = ', name).count(1):
                    self.response.out.write(templates.get_template('msg.html').render(title='注册错误', body='已有同名账号存在，无法完成注册请求。'))
                    return
                    
                if user:
                    user.name = name
                    user.classification = classification
                    user.qq_line = qq_line
                    user.fm_line = fm_line
                else:
                    user = User(user=currentUser, name=name, classification=classification, qq_line=qq_line, fm_line=fm_line)
                try:
                    user.put()
                    if registering:
                        self.response.out.write(templates.get_template('msg.html').render(title='注册成功', body='您的账号已成功建立。'))
                    else:
                        self.response.out.write(templates.get_template('msg.html').render(title='修改成功', body='您的账号已成功修改。'))
                except:
                    self.response.out.write(templates.get_template('msg.html').render(title='注册错误', body='数据库故障，暂时无法完成注册请求。您可以稍后重试。'))